package pri.hillchen.std.consurrent.util.post;

import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import pri.hillchen.std.consurrent.util.HttpclientManager;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by hillchen on 2018/2/10.
 */
public class MapPostRequestParamsEntityFactory implements RequestParamsEntityFactory{
    private static Logger LOGGER = Logger.getLogger(MapPostRequestParamsEntityFactory.class);
    private String charCode = "UTF-8";
    private Map<String,String> params;

    public MapPostRequestParamsEntityFactory(Map<String, String> params) {
        this.params = params;
    }

    public MapPostRequestParamsEntityFactory(String charCode, Map<String, String> params) {
        this.charCode = charCode;
        this.params = params;
    }

    @Override
    public HttpEntity createRequestParamsEntity() {
        if (params != null && !params.isEmpty()) {
            List<BasicNameValuePair> nvps = new ArrayList<>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            // 这里设置的是返回结果编码,大多数都是UTF-8,如果乱码,可以查看网页的meta中的content的编码.如果是GBK,这里改为GBK即可.
            // 这里entity只能读取一次,想要读取多次,百度一下.
            try {
                return new UrlEncodedFormEntity(nvps, charCode);
            } catch (UnsupportedEncodingException e) {
                LOGGER.error("创建post请求参数实体失败!");
                return null;
            }
        }
        return null;
    }
}
